package com.gitee.ixtf.sap.application

import com.gitee.ixtf.sap.Constant.SAP_DESTINATION_NAME
import com.gitee.ixtf.sap.Constant.SAP_JCO_ASHOST
import com.gitee.ixtf.sap.Constant.SAP_JCO_CLIENT
import com.gitee.ixtf.sap.Constant.SAP_JCO_LANG
import com.gitee.ixtf.sap.Constant.SAP_JCO_PASSWD
import com.gitee.ixtf.sap.Constant.SAP_JCO_POOL_CAPACITY
import com.gitee.ixtf.sap.Constant.SAP_JCO_SYSNR
import com.gitee.ixtf.sap.Constant.SAP_JCO_USER
import com.google.common.collect.Maps
import com.sap.conn.jco.ext.DestinationDataEventListener
import com.sap.conn.jco.ext.DestinationDataProvider
import com.sap.conn.jco.ext.DestinationDataProvider.*
import java.util.*

class SapDestinationDataProvider : DestinationDataProvider {
  private lateinit var eL: DestinationDataEventListener
  private val storage = Maps.newConcurrentMap<String, Properties>()

  override fun getDestinationProperties(destinationName: String?): Properties {
    val destName = destinationName?.takeIf { it.isNotBlank() } ?: SAP_DESTINATION_NAME
    return storage.computeIfAbsent(destName) { loadProperties(destName) }
  }

  @Synchronized
  private fun loadProperties(destName: String) =
      Properties().apply {
        setProperty(JCO_ASHOST, SAP_JCO_ASHOST)
        setProperty(JCO_SYSNR, SAP_JCO_SYSNR)
        setProperty(JCO_CLIENT, SAP_JCO_CLIENT)
        setProperty(JCO_USER, SAP_JCO_USER)
        setProperty(JCO_PASSWD, SAP_JCO_PASSWD)
        setProperty(JCO_LANG, SAP_JCO_LANG)
        setProperty(JCO_POOL_CAPACITY, "$SAP_JCO_POOL_CAPACITY")

        println("DestinationDataProvider: $destName")
        println(this)
      }

  override fun setDestinationDataEventListener(el: DestinationDataEventListener) {
    this.eL = el
  }

  override fun supportsEvents(): Boolean = true
}
